﻿using CoreColution.EntityDto.Common;
using CoreSolution.IService.Common;
using CoreSolution.Tools;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;

namespace CoreSolution.Service.Common
{
    public class FileUploadService: IFileUploadService
    {

        private readonly IHostingEnvironment hostingEnv;

        public FileUploadService(IHostingEnvironment hostingEnv)
        {
            this.hostingEnv = hostingEnv;
        }
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="files">文件对象</param>
        /// <returns>success:是否上传成功  message:提示信息  fileReturn:返回上传文件的名称和路径</returns>
        public (bool success, string message, FileReturnDto fileReturn) UploadFile(IFormFileCollection files)
        {
            //允许上传的文件类型
            var fileTypes = ConfigHelper.GetSectionValue("UploadFiletype");
            var size = files.Sum(f => f.Length);

            //size > 1000MB refuse upload !
            if (size > 1048576000)
            {
                return (false, "文件大小超过限制", null);
            }

            string filePathResultList = "";
            string fileNameResultList = "";
            string videoSnapshotUrl = "";

            foreach (var file in files)
            {
                var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                if (fileNameResultList != "")
                {
                    fileNameResultList += ",";
                }

                fileNameResultList += fileName;

                var filePath = hostingEnv.WebRootPath + $@"\Files\";

                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
                var suffix = fileName.Split('.')[1];

                if (!fileTypes.Contains(suffix.ToLower()))
                {
                    return (false, "文件类型不正确", null);
                }

                fileName = Guid.NewGuid() + "." + fileName.Split('.')[1];

                var fileFullName = filePath + fileName;

                using (FileStream fs = File.Create(fileFullName))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }

                if (filePathResultList != "")
                {
                    filePathResultList += ",";
                }

                filePathResultList += $"/Files/{fileName}";

                if (IsVideoFile(suffix.ToLower()))
                {
                    var snapshot = GetSnapshotImageFromVideo(fileFullName);
                    if (!string.IsNullOrWhiteSpace(snapshot))
                    {
                        videoSnapshotUrl = $"/Files/{snapshot}";
                    }
                }
            }

            var fileReturn = new FileReturnDto { FileNames = fileNameResultList, FileUrls = filePathResultList, VideoSnapshotUrl = videoSnapshotUrl };
            var message = $"{files.Count} file(s) /{size} bytes uploaded successfully!";

            return (true, message, fileReturn);
        }

        /// <summary>
        /// 判断文件是否是视频文件
        /// </summary>
        /// <param name="suffix">文件后缀</param>
        /// <returns></returns>
        private bool IsVideoFile(string suffix)
        {
            string[] videoFormatList = { "rm", "rmvb", "mp4", "3gp", "mov", "avi", "mkv", "flv" };
            return videoFormatList.Contains(suffix);
        }

        /// <summary>
        /// 从视频文件中抓取快照截图
        /// </summary>
        /// <param name="vFileName">视频文件地址(绝对路径)</param>
        /// <returns></returns>
        private string GetSnapshotImageFromVideo(string vFileName)
        {

            //取得ffmpeg.exe的路径,路径配置在appsetting.json中,如: "ffmpeg": "E:\\temp\\ffmpeg.exe"

            var ffmpeg = ConfigHelper.GetSectionValue("ffmpeg");

            if (!File.Exists(ffmpeg))
            {
                throw new FileNotFoundException("ffmpeg.exe not found in config path.");
            }

            var filePath = hostingEnv.WebRootPath + $@"\Files\";
            var imageName = $"{Guid.NewGuid()}_snapshot.png";
            var imageFullName = filePath + imageName;

            //截图的尺寸大小
            var FlvImgSize = "200x200";

            var startInfo = new System.Diagnostics.ProcessStartInfo(ffmpeg)
            {
                WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,

                //此处组合成ffmpeg.exe文件需要的参数即可,此处命令在ffmpeg 0.4.9调试通过

                //-ss后跟的时间单位为秒
                Arguments = " -i " + vFileName + " -y -f image2 -ss 5 -t 0.001 -s " + FlvImgSize + " " + imageFullName
            };

            try
            {
                System.Diagnostics.Process.Start(startInfo);

            }
            catch (Exception ex)
            {
                return "";
                throw ex;
            }
            return imageName;
        }
    }
}
